
import { MicroframeworkLoader, MicroframeworkSettings } from "microframework";
import { createExpressServer, Action } from "routing-controllers";
import * as figlet from 'figlet'
import { CalendarController } from '../api/controller/CalendarController';
import { SpiderController } from '../api/controller/SpiderController';
import * as express from 'express';
import * as bodyParser from 'body-parser';
import * as path from 'path';
import compression from 'compression';
import errorHandler from "errorhandler";
import * as ejs from 'ejs';
import { UserSession } from '../api/UserDecorator'
// import * as secrets from '../lib/utils/secrets';

export const expressLoader: MicroframeworkLoader = (settings: MicroframeworkSettings | undefined) => {

    if (settings) {
        const expressApp: express.Application = createExpressServer({
            cors: true,
            controllers: [CalendarController, SpiderController],
            routePrefix: "api",
            //授权检查
            // authorizationChecker: (action: Action) => {
            //     const token = action.request.headers["authorization"];
            //     UserSession.token = !token ? '' : (<string>token).replace('Bearer ', '');
            //     return token;
            // }

        });

        expressApp.set("view engine", "ejs");
        expressApp.set('views', path.join(__dirname, '../views'));

        // expressApp.use(cors());

        expressApp.use(compression({
            filter: (req, res) => {
                if (req.headers['x-no-compression']) {
                    return false
                }
                return compression.filter(req, res);
            }
        }));

        expressApp.use(bodyParser.urlencoded({
            extended: true
        }));

        expressApp.use(bodyParser.json());

        var options = {
            dotfiles: 'ignore',
            etag: false,
            extensions: ['htm', 'html'],
            index: false,
            maxAge: '1d',
            redirect: false,
            setHeaders: function (res: any, path: any, stat: any) {
                res.set('x-timestamp', Date.now());
            }
        }
        let staticFolder = path.join(__dirname, '..', 'public');

        expressApp.use('/static', express.static(staticFolder, options));

        expressApp.use(errorHandler());


        // expressApp.use('/*', function (req, res, next) {
        //     console.log(req.path);
        //     next();
        // });

        // expressApp.use(function (req, res) {  
        //     res.send('404: Page not Found');
        // });

        let port = process.env.PORT || 3000;
        expressApp.set("port", port);

        expressApp.listen(expressApp.get('port'), () => {

            console.log(
                "  App is running at http://localhost:%d in %s mode",
                expressApp.get("port"),
                expressApp.get("env")
            );
            figlet.text('Das', (err, result) => {
                //Ignore
                if (err) {
                    return;
                }
                console.log(result);
            })
            console.log("  Press CTRL-C to stop\n");
        });
        settings.setData('express_app', expressApp);
    }

}